import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { JwtModule } from '@nestjs/jwt';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserModule } from './user/user.module';
import { User } from './user/entities/user.entity';
import { Role } from './user/entities/role.entity';
import { Permission } from './user/entities/permission.entity';
import { RedisModule } from './redis/redis.module';

import { APP_GUARD } from '@nestjs/core';
import { LoginGuard } from './login.guard';
import { PermissionGuard } from './permission.guard';
import { UploadModule } from './upload/upload.module';
import { ConfigModule } from '@nestjs/config';
import yamlConfig from './env/loadEnv';
import { ConfigService } from '@nestjs/config';

import {
  HeaderResolver,
  I18nModule,
  QueryResolver,
  CookieResolver,
  AcceptLanguageResolver,
} from 'nestjs-i18n';

@Module({
  imports: [
    I18nModule.forRoot({
      // 默认语言：英语
      fallbackLanguage: 'en',
      // 前端可以从哪里传语言（query参数、header头、 cookie、 accept-language 请求头）
      resolvers: [
        new QueryResolver(['lang', 'l']),
        new HeaderResolver(['x-custom-lang']),
        new CookieResolver(['lang']),
        AcceptLanguageResolver,
      ],
      loaderOptions: {
        path: __dirname + '/i18n/',
        watch: true,
      },
    }),
    ConfigModule.forRoot({
      isGlobal: true,
      load: [yamlConfig],
      cache: true,
    }),
    JwtModule.register({
      secret: 'duolamon', // 指定加密密钥
      global: true,
      signOptions: { expiresIn: '1d' }, // 指定token有效期
    }),
    TypeOrmModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => {
        return {
          type: 'mysql',
          host: configService.get('db.mysql.host'),
          port: configService.get('db.mysql.port'),
          username: configService.get('db.mysql.username'),
          password: configService.get('db.mysql.password'),
          database: configService.get('db.mysql.database'),
          synchronize: true,
          logging: true,
          entities: [User, Role, Permission],
          poolSize: 10,
          connectorPackage: 'mysql2',
          extra: {
            authPlugins: 'sha256_password',
          },
        };
      },
    }),
    UserModule,
    RedisModule,
    UploadModule,
  ],
  controllers: [AppController],
  providers: [
    AppService,
    {
      provide: APP_GUARD,
      useClass: LoginGuard,
    },
    {
      provide: APP_GUARD,
      useClass: PermissionGuard,
    },
  ],
})
export class AppModule {}
